package model

import (
	"encoding/json"
	"fmt"

	"github.com/invopop/jsonschema"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/bsontype"
)

type (
	Cpu struct {
		FractionOfUsage float64

		Unit CpuUnit
	}

	CpuUnit int32
)

const (
	cpuUnitCore = 0
)

func (Cpu) JSONSchema() *jsonschema.Schema {
	return &jsonschema.Schema{
		OneOf: []*jsonschema.Schema{
			{Type: "number"},
			{Type: "string"},
		},
	}
}

func (d *Cpu) UnmarshalJSON(data []byte) error {
	var tempValue64 float64
	if err := json.Unmarshal(data, &tempValue64); err != nil {
		return fmt.Errorf("unmarshalling cpu failed: %w", err)
	}
	// edit in case of using other cpu units
	*d = Cpu{
		FractionOfUsage: tempValue64,
		Unit:            cpuUnitCore,
	}
	return nil
}

func (d *Cpu) MarshalJSON() ([]byte, error) {
	if d.Unit == cpuUnitCore {
		return json.Marshal(d.FractionOfUsage)
	} else {
		// edit in case of other using other cpu units

		return []byte("null"), fmt.Errorf("wrong cpu units, should be like cpuUnitCore")
	}
}

func (d *Cpu) UnmarshalBSONValue(t bsontype.Type, data []byte) error {
	raw := bson.RawValue{Type: t, Value: data}
	switch t {
	case bsontype.Double:
		resFloat64 := raw.Double()
		*d = Cpu{
			FractionOfUsage: resFloat64,
			Unit:            cpuUnitCore,
		}
		return nil
	default:
		return fmt.Errorf("cannot unmarshall cpu with type '%s'", t)
	}
}

func (d *Cpu) MarshalBSONValue() (bsontype.Type, []byte, error) {
	if d.Unit == cpuUnitCore {
		return bson.MarshalValue(d.FractionOfUsage)
	} else {
		// edit in case of using other cpu units
		return bsontype.Null, nil, fmt.Errorf("wrong cpu units, should be like cpuUnitCore")
	}
}

func (d *Cpu) ToKubernetesCpu() (int64, error) {
	if d.FractionOfUsage == 0 {
		return 0, nil
	}

	if d.FractionOfUsage < 0 {
		return 0, fmt.Errorf("cpu units can only be non-negative")
	}
	if d.FractionOfUsage < 0.001 {
		return 0, fmt.Errorf("cannot use such small cpu resource: %f", d.FractionOfUsage)
	}
	return int64(d.FractionOfUsage * 1000), nil
}
